package com.senmo.request.Volley;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;

import lx.af.utils.log.Log;

/**
 * author: lx
 * date: 16-1-4
 */
public class PostJsonBodyRequest extends Request<String> {

    /** Default charset for JSON request. */
    protected static final String PROTOCOL_CHARSET = "utf-8";

    /** Content type for request. */
    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    private Response.Listener<String> mListener;
    private VolleyError mError;
    private String mRequestBody;

    public PostJsonBodyRequest(String url, String requestBody,
                               Response.Listener<String> listener,
                               Response.ErrorListener errListener) {
        super(Method.POST, url, errListener);
        mRequestBody = requestBody;
        Log.d("liuxu", "11111 request json body: " + mRequestBody);
        mListener = listener;
    }

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }

    @Override
    public void deliverError(VolleyError error) {
        mError = error;
        super.deliverError(error);
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    public byte[] getBody() {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }

    public int getHttpStatusCode() {
        if (mError != null && mError.networkResponse != null) {
            return mError.networkResponse.statusCode;
        } else {
            return 200;
        }
    }

}
